/*
 * Copyright 2009 Armando Blancas
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package taskgraph.channels;

import java.io.IOException;
import java.util.Formatter;
import java.util.Locale;

import taskgraph.Config;
import taskgraph.pipes.CharInputPipe;
import taskgraph.pipes.CharOutputPipe;
import taskgraph.ports.CharInputPort;
import taskgraph.ports.CharOutputPort;


/**
 * A channel that transports {@code char} values.
 * <p>Characters are stored into, and read from, a FIFO buffer in their
 * primitive type representation without being byte-streamed.  
 * 
 * @author Armando Blancas
 */
public class CharChannel {
    
    private static final int DEFAULT_BUFFER_SIZE = Config.get().channelCapacity();
	
	private final CharOutputPipe output;
    private final CharInputPipe input;
    private final CharOutputPort outputPort;
    private final CharInputPort inputPort;
    
    private final char[] lineSeparator;
    
    /**
     * Creates a channel with the default buffer size.
     */
    public CharChannel() {
    	this(DEFAULT_BUFFER_SIZE);
    }
    
    /**
     * Creates a channel with the passed buffer size.
     * 
     * @param bufferSize The buffer capacity in bytes. 
     */
    public CharChannel(final int bufferSize) {
        if (bufferSize <= 0) {
            throw new IllegalArgumentException("CharChannel bufferSize <= 0");
         }
        
		try {
			output = new CharOutputPipe();
			input = new CharInputPipe(output, bufferSize);
			outputPort = new OutputPort();
			inputPort = new InputPort();
			
			lineSeparator = System.getProperty("line.separator").toCharArray();
		} catch (IOException e) {
			throw new Error(e);
		}
    }
    
    /**
     * Gets a reference to this class as an output port.
     * 
     * @return An output interface to this channel.
     */
    public CharOutputPort getOutputPort() {
    	return outputPort;
    }
    
    /**
     * Gets a reference to this class as an input port.
     * 
     * @return An input interface to this channel.
     */
    public CharInputPort getInputPort() {
    	return inputPort;
    }

    /**
     * A private implementation of the char output port. It has direct access
     * to this channel and the char input port. Instances of this class are 
     * published through the CharOutputPort interface. 
     */
    private class OutputPort implements CharOutputPort {
    	
    	@Override
    	public CharOutputPort write(char c) throws IOException {
    		output.write(c);
    		return this;
    	}

    	@Override
    	public CharOutputPort write(char[] c) throws IOException {
    		output.write(c);
    		return this;
    	}

    	@Override
    	public CharOutputPort write(char[] c, int off, int len) 
    	throws IOException {
    		output.write(c, off, len);
    		return this;
    	}

    	@Override
    	public CharOutputPort print(String s) throws IOException {
    		write(s.toCharArray());
    		return this;
    	}

    	@Override
    	public CharOutputPort println() throws IOException {
    		newLine();
    		return this;
    	}

    	@Override
    	public synchronized CharOutputPort println(String s) 
    	throws IOException {
    		write(s.toCharArray());
    		newLine();
    		return this;
    	}

    	@Override
    	public CharOutputPort printf(String format, Object... args)
    	throws IOException {
    		char[] c = new Formatter()
    					   .format(format, args).toString().toCharArray();
    		write(c, 0, c.length);
    		return this;
    	}

    	@Override
    	public CharOutputPort printf(Locale l, String format, Object... args)
    	throws IOException {
    		char[] c = new Formatter(l)
    				       .format(format, args).toString().toCharArray();
    		write(c, 0, c.length);
    		return this;
    	}

    	@Override
    	public void close() {
    		output.close();
    	}
    	
        private synchronized void newLine() {
       		try {
    			write(lineSeparator, 0, lineSeparator.length);
    		} catch (IOException e) {
    			// best effort
    		}
        }
    	
    }

    /**
     * A private implementation of the char input port. It has direct access
     * to this channel and the char output port. Instances of this class are 
     * published through the CharInputPort interface. 
     */
    private class InputPort implements CharInputPort {

    	@Override
		public char read() throws IOException {
			return input.read();
		}
	
		@Override
		public int read(char[] c) throws IOException {
			return input.read(c);
		}
	
		@Override
		public int read(char[] c, int off, int len) throws IOException {
			return input.read(c, off, len);
		}
	
		@Override
	    public String readLine() throws IOException {
			return input.readLine();
		}
	
		@Override
	    public final int skipChars(int n) throws IOException {
			return input.skipChars(n);
		}
		@Override
		public void close() {
			input.close();
		}
	
    }

}
